<template>
  <div class="score-rule-container">
    <el-card class="header-card">
      <div class="header-content">
        <h2>计算规则管理</h2>
        <el-button type="primary" @click="handleAddRule">添加规则</el-button>
      </div>
    </el-card>

    <el-card class="rule-card">
      <el-table :data="ruleList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="type" label="规则类型" min-width="150">
          <template #default="scope">
            <el-tag :type="getRuleTypeTag(scope.row.type)">{{ getRuleTypeText(scope.row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分值" width="100" align="center">
          <template #default="scope">
            <span class="score">{{ scope.row.score }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="规则描述" min-width="250" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="small" @click="handleEditRule(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDeleteRule(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑规则对话框 -->
    <el-dialog 
      :title="dialogType === 'add' ? '添加计算规则' : '编辑计算规则'" 
      v-model="dialogVisible" 
      width="500px"
    >
      <el-form 
        :model="ruleForm" 
        :rules="ruleFormRules" 
        ref="ruleFormRef" 
        label-width="100px"
      >
        <el-form-item label="规则类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择规则类型" style="width: 100%">
            <el-option v-for="(label, value) in ruleTypeOptions" :key="value" :label="label" :value="value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分值" prop="score">
          <el-input-number v-model="ruleForm.score" :min="1" :max="1000" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="规则描述" prop="description">
          <el-input v-model="ruleForm.description" type="textarea" :rows="3" placeholder="请输入规则描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRuleForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 规则类型选项
const ruleTypeOptions = {
  'paper': '论文',
  'project': '科研项目',
  'patent': '专利',
  'award': '奖项',
  'paper_impact': '论文影响因子',
  'project_funding': '项目经费',
  'national_project': '国家级项目',
  'provincial_project': '省级项目',
  'municipal_project': '市级项目',
  'horizontal_project': '横向项目',
  'invention_patent': '发明专利',
  'utility_model_patent': '实用新型专利',
  'design_patent': '外观设计专利',
  'national_award': '国家级奖项',
  'provincial_award': '省级奖项',
  'municipal_award': '市级奖项',
  'school_award': '校级奖项'
}

// 获取规则类型标签
const getRuleTypeTag = (type) => {
  if (type.includes('paper')) return 'success'
  if (type.includes('project')) return 'primary'
  if (type.includes('patent')) return 'warning'
  if (type.includes('award')) return 'danger'
  return 'info'
}

// 获取规则类型文本
const getRuleTypeText = (type) => {
  return ruleTypeOptions[type] || type
}

// 规则列表数据
const ruleList = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const ruleFormRef = ref(null)
const submitLoading = ref(false)

// 规则表单
const ruleForm = reactive({
  id: null,
  type: '',
  score: 0,
  description: ''
})

// 表单验证规则
const ruleFormRules = {
  type: [
    { required: true, message: '请选择规则类型', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请输入分值', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入规则描述', trigger: 'blur' }
  ]
}

// 获取规则列表
const fetchRuleList = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:8081/api/score-rule/list')
    if (response.data.code === 200) {
      ruleList.value = response.data.data || []
    } else {
      ElMessage.error(response.data.msg || '获取规则列表失败')
    }
  } catch (error) {
    console.error('获取规则列表错误:', error)
    ElMessage.error('获取规则列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 添加规则
const handleAddRule = () => {
  dialogType.value = 'add'
  resetRuleForm()
  dialogVisible.value = true
}

// 编辑规则
const handleEditRule = (row) => {
  dialogType.value = 'edit'
  resetRuleForm()
  
  // 填充表单数据
  Object.keys(ruleForm).forEach(key => {
    if (key in row) {
      ruleForm[key] = row[key]
    }
  })
  
  dialogVisible.value = true
}

// 删除规则
const handleDeleteRule = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除规则 "${row.description}" 吗？`,
      '删除规则',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const params = new URLSearchParams()
    params.append('id', row.id)
    
    const response = await axios.post('http://localhost:8081/api/score-rule/delete', params)
    
    if (response.data.code === 200) {
      ElMessage.success('删除规则成功')
      fetchRuleList() // 刷新列表
    } else {
      ElMessage.error(response.data.msg || '删除规则失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除规则错误:', error)
      ElMessage.error('删除规则失败，请检查网络连接')
    }
  }
}

// 重置规则表单
const resetRuleForm = () => {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields()
  }
  
  ruleForm.id = null
  ruleForm.type = ''
  ruleForm.score = 0
  ruleForm.description = ''
}

// 提交规则表单
const submitRuleForm = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const url = dialogType.value === 'add' 
          ? 'http://localhost:8081/api/score-rule/add' 
          : 'http://localhost:8081/api/score-rule/update'
        
        const response = await axios.post(url, ruleForm)
        
        if (response.data.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加规则成功' : '编辑规则成功')
          dialogVisible.value = false
          fetchRuleList() // 刷新列表
        } else {
          ElMessage.error(response.data.msg || (dialogType.value === 'add' ? '添加规则失败' : '编辑规则失败'))
        }
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加规则错误:' : '编辑规则错误:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加规则失败，请检查网络连接' : '编辑规则失败，请检查网络连接')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 页面加载时获取规则列表
onMounted(() => {
  fetchRuleList()
})
</script>

<style scoped>
.score-rule-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rule-card {
  margin-bottom: 20px;
}

.score {
  font-weight: bold;
  color: #F56C6C;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid #ebeef5;
}

:deep(.el-table__row:hover td) {
  background-color: #f5f7fa;
}
</style>